package me.shibor.study.servlet;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 测试不同范围的变量共享
 * 
 * @author shibor
 *
 */
@WebServlet("/TestShareVar")
public class TestShareVar extends HttpServlet {
	private static final long serialVersionUID = 1L;

    public TestShareVar() {
        super();
    }


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		getVar(request);
		
		setVar(request);
	}
	
	private void getVar(HttpServletRequest request) {
		
		ServletContext context = request.getServletContext();
		HttpSession session = request.getSession();
		
		String context_value = (String)context.getAttribute("context_name");
		String session_value = (String)session.getAttribute("session_name");
		String request_value = (String)request.getAttribute("request_name");
	
		System.out.println("context: " + context_value);
		System.out.println("session: " + session_value);
		System.out.println("request: " + request_value);
	
	}
	
	private void setVar(HttpServletRequest request) {
		
		ServletContext context = request.getServletContext();
		context.setAttribute("context_name", "context_value");
		
		HttpSession session = request.getSession();
		session.setAttribute("session_name", "session_value");
		
		request.setAttribute("request_name", "request_value");
		
		//request.getRequestDispatcher("GetShareVar").forward(request, response);
	}


}
